@namespace BlazorDemos.Shared
@implements IDisposable;

@inject SampleService SampleService;
@inject NavigationManager NavigationManager;

<DropDownComponent DataSource="@cultureData" Value="@culture" OnSelect="@OnSelected"></DropDownComponent>

@code {
    private string culture { get; set; }

    private List<DropDownData> cultureData = new List<DropDownData> {
        new DropDownData() { ID = "en-US", Text = "English" },
        new DropDownData() { ID = "de", Text = "German - Germany*" },
        new DropDownData() { ID = "fr-CH", Text = "French - Switzerland*" },
        new DropDownData() { ID = "zh", Text = "Chinese - China*" },
    };

    // Culture selection event callback handler
    private void OnSelected(DropDownData args)
    {
        var culture = args.ID;
        string currentUri = SampleService.SampleInfo.Url.ToLower();
        string themeName = (NavigationManager.Uri.IndexOf('?') >= 0) ? (NavigationManager.Uri.Split('?')[1]) : null;
        string replacedContent = (themeName != null) ? (currentUri + '?' + themeName) : currentUri;
        var uri = new Uri(NavigationManager.Uri).GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped);
        var path = uri.Replace(replacedContent, "").Trim('/');
        var query = $"?culture={Uri.EscapeDataString(culture)}&" + $"redirectUri={Uri.EscapeDataString(uri)}";
        if (String.IsNullOrEmpty(path))
        {
            NavigationManager.NavigateTo("/Culture/SetCulture" + query, forceLoad: true);
        }
        else
        {
            NavigationManager.NavigateTo("/" + path + "/Culture/SetCulture" + query, forceLoad: true);
        }
    }

    protected override void OnInitialized()
    {
        base.OnInitialized();
        var currentCulture = cultureData.Where(item => item.ID == System.Globalization.CultureInfo.CurrentCulture.Name).ToList();
        if (currentCulture.Any())
        {
            culture = currentCulture.First().Text;
        }
    }

    public void Dispose()
    {
        cultureData = null;
    }
}
